<template>
  <main>
    <div class="logo">
      <i class="iconfont icon-gongzhonghao"></i>
    </div>
    <p class="title-tip">微信授权登录中</p>
  </main>
</template>

<script>
import { Dialog, Toast } from 'vant';
import { getUrl } from 'utils/index'
import { mapActions } from 'vuex';
import * as Api from 'api/index'
import baseURL from 'api/baseUrlConfig'

export default {
  name: 'home-view',
  data() {
    return {
      code: ''
    };
  },
  created() {
    this.$emit('showTabMenu', false);
    // 从 window.location.href 中截取 code 并且赋值
    if(window.location.href.indexOf('code') > 0) { 
      // 此方法仅供参考！！！
      this.code = window.location.href.split('?')[1].split('=')[1].split('&')[0];
      this.handGetUserInfo(this.code);
    } else {
      this.handwxLogin()
    }
  },
  methods: {
    ...mapActions([
      'UnSetPassword',
      'Token',
      'GetUserInfo',
      'SetUserInfo'
    ]),
    handwxLogin() {
      // 重定向地址重定到当前页面，在路径获取 code
      if (this.code === '') {
        let params = {
          appid: baseURL.appid,
          redirect_uri: baseURL.redirect_uri,
          response_type: 'code',
          scope: 'snsapi_userinfo',
          state: 'CSDN_state'
        }
        window.location.href = getUrl(baseURL.wechatOauthUrl, params) + '#wechat_redirect'
      }
    },	
    handGetUserInfo(code) {
      // 调用后端接口，参数为 code 剩下工作量交给后端即可
      Api.WechatAuth({code: this.code}).then(res => {
        // 未绑定手机号
        if (res.data.unBindPhone) {
          this.SetUserInfo({ openid: res.data.info.openid})
          this.$router.push({name: 'BindPhone'})
        } else {
          this.Token(res.data)
          this.GetUserInfo()
          window.location.replace(window.location.origin + '/#/personal')
        }
      }).catch(() => {
        window.location.replace(baseURL.login_uri)
      })
    }
  }
}
</script>

<style lang="less" scoped>
main{
  padding: 0 20px;
}
.logo{
  margin: 40px auto 20px;
  text-align: center;
  i{
    font-size: 40px;
    color: #fff;
    border-radius: 50%;
    padding: 5px;
    background: #4CAF50;
  }
}
.title-tip{
  text-align: center;
  font-size: 14px;
  padding-bottom: 40px;
}
</style>
